package org.example.erp.web.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.erp.domain.SysMenu;
import org.example.erp.mapper.SysMenuMapper;
import org.example.erp.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Value("${spring.profiles.active:default}")
    private String activeProfile; //获取开发环境变量

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(request.getRequestURI().trim().equals("/api/user/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 如果是开发环境则放行
        if(activeProfile.equals("dev")){
            filterChain.doFilter(request, response);
            return;
        }
        String token = extractTokenFromRequest(request);
        // 判断token不为空并且没有过期
        if (token != null && !JwtUtil.isTokenExpired(token)) {
            // 设置认证信息到 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(token));
        }
        filterChain.doFilter(request, response);
    }

    // 提取请求头中的token
    private String extractTokenFromRequest(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }

    // // 解析 token 并返回 Authentication 对象
    private Authentication getAuthentication(String token) {
        Map<String, Object> map = JwtUtil.parseJwt(token);
        List<SysMenu> menus = sysMenuMapper.findMenus(map.get("username").toString(),null);
        // 过滤出有权限标识符的菜单，并提取权限标识符
        List<String> perms =  menus.stream().filter(item-> item.getPerms()!=null)
                 .map(SysMenu::getPerms)
                 .collect(Collectors.toList());
//        System.out.println(perms);
        return new UsernamePasswordAuthenticationToken(map.get("username"),null, AuthorityUtils.createAuthorityList(perms.toArray(new String[0])));
    }
}
